/**
 *  Created by zlgb on 2021-04-14 09:14:19
 *  ------------------修改记录-------------------
 *  修改人      修改日期                 修改目的
 *  zlgb        2021-04-14               创建
 **/
import api from 'src/plugins/http/api';
import axios from 'axios';

export function uploadFile(files: any, cb: (arg: any) => void) {
    const config1 = {
        'headers': { 'Content-Type': 'multipart/form-data' }
    };
    let config2 = {
        'headers': { 'Content-Type': 'application/json' }
    };
    let chunkSize = 10 * 1024 * 1024;
    let fileInfo = {
        'name': [],
        chunkSize,
        'hash': [],
        'fileSize': [],
        'num': 0
    };
    let successNum = 0;
    const reset = () => {
        fileInfo = {
            'name': [],
            chunkSize,
            'hash': [],
            'fileSize': [],
            'num': 0
        };
        successNum = 0;
    };
    const uploadSuccess = () => {
        axios.post(api.uploadSuccess, fileInfo, config2).then((rs2: any) => {
            reset();
            cb(rs2.data);
        });
    };
    const upload = (file: string | Blob) => {
        const formData = new FormData();
        formData.append('image', file);
        axios.post(api.uploadSend, formData, config1).then((rs1: any) => {
            if (rs1.status === 200) {
                successNum += 1;
                // @ts-ignore
                fileInfo.hash.push(rs1.data.data.hash);
                // @ts-ignore
                fileInfo.name.push(file.name);
                // @ts-ignore
                fileInfo.fileSize.push(file.size);
            }
            if (successNum === files.length) {
                uploadSuccess();
            }
        });
    };

    if (files && files.length) {
        files.forEach(async (file: any) => {
            await upload(file);
        });
    }
}
